﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qianjing.APP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using thousandclear.Data;
using thousandClear.Areas.Admin.Models;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class ActivityController : BaseController
    {
        // GET: Shop/Activity
        public ActionResult Index()
        {
            return View();
        }
        // GET: Shop/Activity
        public ActionResult SummerActivity()
        {
            return View();
        }

        // GET: Shop/labor1
        public ActionResult labors()
        {
            return View();
        }

        [HttpPost]
        public string GetPhoneCode(string ccphone)
        {
            Random ran = new Random();
            int RandKey = ran.Next(1000, 9999);

            SendSms tt = new SendSms();
            string msg = "您好，您的验证码为："+ RandKey.ToString() + "【千净家政祝您生活愉快】";
            tt.SendMsg(ccphone, msg);
            return RandKey.ToString();
        }

        //HttpGet: Shop/Activity
        [HttpGet]
        public int Activity(string dilAddressNoGive, string dilAddressNoGet)
        {
            int resp = 1;
            List<D_IntroduceLog> IntroduceLog = new List<D_IntroduceLog>();

            using (var db = new qianjingEntities())
            {
                var GiveOrder = db.T_Order.FirstOrDefault(a => a.toSerialNo == dilAddressNoGive && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                var GetOrder = db.T_Order.FirstOrDefault(a => a.toSerialNo == dilAddressNoGet && a.RowStatus != 0 && a.RowStatus != 2 && a.RowStatus != 4);
                IntroduceLog = db.D_IntroduceLog.Where(a => a.RowStatus == 1).ToList();

                if (GiveOrder == null)
                {
                    resp = 3;
                    return resp;
                }
                if (GetOrder == null)
                {
                    resp = 4;
                    return resp;
                }
                var GiveAddress = db.O_Address.FirstOrDefault(a => a.OASID == GiveOrder.toOAID);
                var GetAddress = db.O_Address.FirstOrDefault(a => a.OASID == GetOrder.toOAID);
                var GiveGood = db.O_Goods.FirstOrDefault(a => a.OGSID == GiveOrder.toOGID);
                var GetGood = db.O_Goods.FirstOrDefault(a => a.OGSID == GetOrder.toOGID);
                if (GiveGood.ogsType == 1 || GiveGood.ogsType == 5)
                {
                    resp = 5;
                    return resp;
                }
                if (GetGood.ogsType == 1 || GetGood.ogsType == 5)
                {
                    resp = 6;
                    return resp;
                }
                if (GiveAddress.oasNo == GetAddress.oasNo)
                {
                    resp = 7;
                    return resp;

                }
                foreach (var item in IntroduceLog)
                {
                    if (item.dilAddressNoGive == dilAddressNoGive)
                    {
                        resp = 2;
                        return resp;
                    }
                }
                UtilNS.Util.WriteLog("resp::" + resp + "++++");
                GetOrder.toTime += 1;
                db.SaveChanges();
                db.D_IntroduceLog.Add(new D_IntroduceLog
                {
                    RowStatus = 1,
                    dilAddressNoGive = dilAddressNoGive,
                    dilAddressNoGet = dilAddressNoGet,
                    CreatedDate = DateTime.Now,
                    diltime = 1,
                });
                db.SaveChanges();

            }


            return resp;
        }

        // GET: Shop/labor
        public ActionResult labor(string code, string state, string openid)
        {
            AppSetting setting = new AppSetting();

            string access_token = "";
            string UserName = "";
            string headImage = "";
            if (string.IsNullOrEmpty(openid))
            {
                var i = GetOpenId(code);
                openid = i.openid;
                access_token = i.access_token;


                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                    return null;
                }
                var tt = GetUserInfo(openid, access_token);
                headImage = tt.headimgurl;
                UserName = tt.nickname;
                UtilNS.Util.WriteLog("UserName::" + UserName);
                UtilNS.Util.WriteLog("openid::" + openid);
            }

            using (var db = new qianjingEntities())
            {
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                if (customer == null)
                {
                    db.O_Customer.Add(new O_Customer
                    {
                        ocOpenid = openid,
                        ocNicName = UserName,
                        ocHeadImage = headImage,
                        CreatedDate = DateTime.Now,
                        RowStatus = 1,
                        ocGrades = 0,
                    });
                    db.SaveChanges();

                }
                else
                {
                    customer.ocHeadImage = headImage;
                    customer.ocNicName = UserName;
                    db.SaveChanges();
                }

            }
            ViewBag.OpenId = openid;
            ViewBag.State = state;
            ViewBag.Code = code;
            return View();
        }
        // GET: Shop/OldCustomer
        public ActionResult OldCustomer(string code, string state, string openid, string n)
        {
            try
            {
                AppSetting setting = new AppSetting();
                ViewBag.n = 0;
                if (!string.IsNullOrEmpty(n))
                {
                    ViewBag.n = n;
                }
                string access_token = "";
                string UserName = "";
                string headImage = "";
                if (string.IsNullOrEmpty(openid))
                {
                    var i = GetOpenId(code);
                    openid = i.openid;
                    access_token = i.access_token;


                    if (string.IsNullOrEmpty(openid))
                    {
                        Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                        return null;
                    }

                    var tt = GetUserInfo(openid, access_token);

                    UserName = tt.nickname;
                    headImage = tt.headimgurl;
                    UtilNS.Util.WriteLog("UserName::" + UserName);
                    UtilNS.Util.WriteLog("openid::" + openid);
                }

                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid.Trim() == openid.Trim());
                    if (customer == null)
                    {
                        db.O_Customer.Add(new O_Customer
                        {
                            ocOpenid = openid,
                            ocNicName = UserName,
                            ocHeadImage = headImage,
                            CreatedDate = DateTime.Now,
                            RowStatus = 1,
                            ocGrades = 0,
                        });
                        db.SaveChanges();

                    }
                    else
                    {
                        customer.ocHeadImage = headImage;
                        customer.ocNicName = UserName;
                    }

                }
                ViewBag.OpenId = openid;
                ViewBag.State = state;
                ViewBag.Code = code;
            }
            catch (Exception ex)
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fshop%2fActivity%2fOldcustomer&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }
            return View();
        }

        // POST: Shop/OldCustomer
        [HttpPost]
        public ActionResult OldCustomer(string data)
        {
            int n = 2;
            AppSetting setting = new AppSetting();
            var post = JObject.Parse(data);
            string openid = post["openid"].Value<string>();
            string phone = post["phone"].Value<string>();
            using (var db = new qianjingEntities())
            {
                var address = db.O_Address.Where(a => a.osaPhone.Trim() == phone.Trim());
                var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid.Trim() == openid.Trim());
                customer.ocIsCanCommon = true;
                UtilNS.Util.WriteLog("老客户手机号:" + phone);
                UtilNS.Util.WriteLog("老客户openid::" + openid);

                if (address == null || customer==null) {
                    n = 1;
                }
                else {

                    customer.ocGrades = address.Sum(aa => aa.oasPoint == null ? 0 : aa.oasPoint);
                    

                    foreach (var item in address)
                    {
                        item.oasOCID = (int)customer.OCID;

                    }
                    

                    using (var db2 = new qianjingEntities())
                    {
                        foreach (var item in address)
                        {
                            var order = db2.T_Order.Where(a => a.toOAID == item.OASID).ToList();
                            foreach (var i in order)
                            {
                                i.toOCID = int.Parse(customer.OCID.ToString());
                               
                            }
                        }

                        db2.SaveChanges();
                    }

                    db.SaveChanges();
                }
            }

            RouteValueDictionary dicgt = new RouteValueDictionary();
            dicgt.Add("openid", openid);
            dicgt.Add("n", n);

            Response.Redirect("~/Shop/Activity/OldCustomer?openid=" + openid + "&n=" + n);

            return null;


        }
        // GET: Shop/Aunt
        public ActionResult Aunt(string code, string state, string openid,string n)
        {
            AppSetting setting = new AppSetting();
            ViewBag.n = 0;
            if (!string.IsNullOrEmpty(n)) {

                ViewBag.n = n;
            }
            string access_token = "";
            string UserName = "";
            if (string.IsNullOrEmpty(openid))
            {
                var i = GetOpenId(code);
                openid = i.openid;
                access_token = i.access_token;


                if (string.IsNullOrEmpty(openid))
                {
                    Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                    return null;
                }
                UserName = GetUserInfo(openid, access_token).nickname;
                UtilNS.Util.WriteLog("UserName::" + UserName);
                UtilNS.Util.WriteLog("openid::" + openid);
            }

            ViewBag.OpenId = openid;
            ViewBag.State = state;
            ViewBag.Code = code;

            return View();
        }

        [HttpPost]
        public ActionResult Aunt(string data)
        {
            AppSetting setting = new AppSetting();
            int n = 2;
            var post = JObject.Parse(data);
            string openid = post["openid"].Value<string>();
            string phone = post["phone"].Value<string>();
            using (var db = new qianjingEntities())
            {
                var aunt = db.O_Aunt.FirstOrDefault(a => a.oatPhone == phone);

                if (aunt != null)
                {
                    aunt.oatOpenid = openid;
                    db.SaveChanges();
                }
                else {
                    n = 1;
                }
            }
            RouteValueDictionary dicgt = new RouteValueDictionary();
            dicgt.Add("openid", openid);
            dicgt.Add("n", n);
            return RedirectToAction("Aunt", dicgt);


        }



        public ActionResult ExperienceActivity(string code, string state, string openid)
        {
            AppSetting setting = new AppSetting();
            List<ProjectModel> list = new List<ProjectModel>();
            try
            {


                string access_token = "";
                string UserName = "";
                string headImage = "";
                if (string.IsNullOrEmpty(openid))
                {
                    var i = GetOpenId(code);
                    openid = i.openid;
                    access_token = i.access_token;


                    if (string.IsNullOrEmpty(openid))
                    {
                        Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                        return null;
                    }

                    var tt = GetUserInfo(openid, access_token);
                    headImage = tt.headimgurl;
                    UserName = tt.nickname;
                    UtilNS.Util.WriteLog("UserName::" + UserName);
                    UtilNS.Util.WriteLog("openid::" + openid);
                }

                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                    if (customer == null)
                    {
                        db.O_Customer.Add(new O_Customer
                        {
                            ocOpenid = openid,
                            ocNicName = UserName,
                            CreatedDate = DateTime.Now,
                            ocHeadImage = headImage,
                            RowStatus = 1,
                            ocGrades = 0,
                        });
                        db.SaveChanges();

                    }
                    else
                    {
                        customer.ocHeadImage = headImage;
                        customer.ocNicName = UserName;
                        db.SaveChanges();
                    }

                }
                ViewBag.OpenId = openid;
                ViewBag.State = state;
                ViewBag.Code = code;

                using (var db = new qianjingEntities())
                {
                    var records = db.D_item.OrderBy(a => a.DIMID).Where(a => a.RowStatus == 1 && a.dimType == 3).ToList();
                    foreach (var item in records)
                    {
                        list.Add(new ProjectModel
                        {
                            dimDesc = item.dimDesc,
                            dimName = item.dimName,
                        });
                    }
                    var Good = db.O_Goods.Where(a => a.RowStatus == 1 && a.ogsType == 7).ToList();
                    ViewBag.Good = Good;
                }


                ViewBag.OpenId = openid;
            }
            catch (Exception ex)
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fshop%2fExperience&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }
            return View(list);
        }



        // POST: Shop/ExperienceActivity
        [HttpPost]
        public ActionResult ExperienceActivity(string data)
        {
            AppSetting setting = new AppSetting();
            var post = JObject.Parse(data);
            string OGSID = post["OGSID"].Value<string>();
            string price = post["price"].Value<string>();
            string OpenId = post["OpenId"].Value<string>();
            int hour = post["hour"].Value<int>();
            string Number = DateTime.Now.ToString("yyMMddHHmmss");
            Random example = new Random();
            int Numradom = example.Next(10000, 99999);
            Number = Number + Numradom.ToString();
            using (var db = new qianjingEntities())
            {
                var toOCID = db.O_Customer.FirstOrDefault(a => a.ocOpenid == OpenId).OCID;

                db.T_Order.Add(new T_Order
                {
                    toSerialNo = Number,
                    toOCID = Convert.ToInt16(toOCID),
                    toTotalRate = Convert.ToDecimal(price),
                    toTime = 1,
                    toGoodNum = hour,
                    toOGID = Convert.ToInt16(OGSID),               
                    RowStatus = 0,
                    CreatedDate = DateTime.Now
                });
                db.SaveChanges();
            }
            Response.Redirect("../Address/Index?openid="+OpenId+"&order="+Number);
            return RedirectToAction("");
        }

        //HttpGet:Shop/ExperienceActivity
        [HttpGet]
        public int ChangPeople(int id)
        {
            int Goodid=1;
            UtilNS.Util.WriteLog("id:" + id);
            using (var db = new qianjingEntities())
            {

                var query = db.O_Goods.FirstOrDefault(a => a.ogsSalePrice == id&&a.ogsType==7);
                Goodid =Convert.ToInt16(query.OGSID);  
            }
            return Goodid;


        }
    }
}